package cmd

import (
	"fmt"
	"os/exec"
	"strings"
)

// getGitLog 获取Git提交记录
func getGitLog(limit int, author string, branch string) (string, error) {
	// 首先检查 git 命令是否存在
	if _, err := exec.LookPath("git"); err != nil {
		return "", fmt.Errorf("未找到 git 命令。请确保已安装 Git 并添加到系统 PATH 中。\nGit command not found. Please make sure Git is installed and added to PATH.")
	}

	// 检查当前目录是否是 Git 仓库
	if err := exec.Command("git", "rev-parse", "--git-dir").Run(); err != nil {
		return "", fmt.Errorf("当前目录不是 Git 仓库。请在 Git 项目目录下执行此命令。\nNot a git repository. Please run this command in a Git project directory.")
	}

	// 修改格式以包含时间戳
	args := []string{"log", fmt.Sprintf("-%d", limit), "--pretty=format:%at%n%B%n==COMMIT_END=="}
	
	if author != "" {
		args = append(args, fmt.Sprintf("--author=%s", author))
	}

	if branch != "" {
		// 检查分支是否存在
		if err := exec.Command("git", "show-ref", "--verify", "--quiet", "refs/heads/"+branch).Run(); err != nil {
			// 检查是否是远程分支
			if err := exec.Command("git", "show-ref", "--verify", "--quiet", "refs/remotes/origin/"+branch).Run(); err != nil {
				return "", fmt.Errorf("分支 '%s' 不存在。\n请使用 'git branch' 查看可用分支。\nBranch '%s' not found.\nUse 'git branch' to see available branches.", branch, branch)
			}
		}
		args = append(args, branch)
	}

	cmd := exec.Command("git", args...)
	cmd.Dir = "."
	output, err := cmd.Output()
	if err != nil {
		if exitErr, ok := err.(*exec.ExitError); ok {
			// 获取错误输出
			stderr := string(exitErr.Stderr)
			if strings.Contains(stderr, "not a git repository") {
				return "", fmt.Errorf("当前目录不是 Git 仓库。请在 Git 项目目录下执行此命令。\nNot a git repository. Please run this command in a Git project directory.")
			}
			if strings.Contains(stderr, "bad revision") {
				return "", fmt.Errorf("无效的分支名或引用。\n请使用 'git branch' 查看可用分支。\nInvalid branch name or reference.\nUse 'git branch' to see available branches.")
			}
			return "", fmt.Errorf("执行 git log 时出错：%s\nError executing git log: %s", stderr, stderr)
		}
		return "", fmt.Errorf("执行 git log 时出错：%v\nError executing git log: %v", err, err)
	}

	// 检查是否有提交记录
	if len(output) == 0 {
		if author != "" {
			return "", fmt.Errorf("未找到指定作者的提交记录。\nNo commits found for the specified author.")
		}
		if branch != "" {
			return "", fmt.Errorf("在分支 '%s' 上未找到提交记录。\nNo commits found on branch '%s'.", branch, branch)
		}
		return "", fmt.Errorf("仓库中没有提交记录。\nNo commits found in the repository.")
	}

	return string(output), nil
}

// getGitUserEmail 获取 Git 用户邮箱
func getGitUserEmail() (string, error) {
	cmd := exec.Command("git", "config", "user.email")
	output, err := cmd.Output()
	if err != nil {
		if _, ok := err.(*exec.ExitError); ok {
			return "", fmt.Errorf("未找到 Git 用户邮箱配置。请使用 'git config user.email' 设置。\nGit user email not found. Please set it using 'git config user.email'.")
		}
		return "", fmt.Errorf("获取 Git 用户邮箱时出错：%v\nError getting Git user email: %v", err, err)
	}
	return strings.TrimSpace(string(output)), nil
}

// getGitBranches 获取所有分支
func getGitBranches() ([]string, error) {
	cmd := exec.Command("git", "branch", "--list")
	output, err := cmd.Output()
	if err != nil {
		if _, ok := err.(*exec.ExitError); ok {
			return nil, fmt.Errorf("获取分支列表失败。请确保当前目录是 Git 仓库。\nFailed to get branch list. Make sure you're in a Git repository.")
		}
		return nil, fmt.Errorf("获取分支列表时出错：%v\nError getting branch list: %v", err, err)
	}

	var branches []string
	for _, line := range strings.Split(string(output), "\n") {
		branch := strings.TrimSpace(strings.TrimPrefix(line, "*"))
		if branch != "" {
			branches = append(branches, branch)
		}
	}
	return branches, nil
} 